package com.xuecheng.test.rabbitmq;


import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * rabbitmq队列生产者入门程序
 */
public class Consumer01 {
    private static final String QUEUE_NAME = "helloWorld";

    public static void main(String[] args) {
        // 通过链接工程创建链接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/");
        Connection connection = null;
        try {
            // 建立新的链接
            connection = connectionFactory.newConnection();
            // 建立会话通道, 所有的请求都是在通道完成的,通道之间相互独立
            Channel channel = connection.createChannel();
            // 声明队列
            channel.queueDeclare(QUEUE_NAME, true, false, false, null);
            // 监听队列
            channel.basicConsume(QUEUE_NAME, true, new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    System.out.println("consumerTag = " + consumerTag);
                    System.out.println("envelope = " + envelope);
                    System.out.println("properties = " + properties);
                    System.out.println(new String(body, StandardCharsets.UTF_8));
                }
            });
            System.in.read();
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        }
    }
}
